const express = require("express");
const jwt = require("jsonwebtoken");
const assert = require("http-assert");

const User = require("../../models/User");

const router = express.Router({
  mergeParams: true,
});

//用户登录
router.post("/login", async (req, res) => {
  const { username, password } = req.body;
  //根据用户名找用户

  const user = await User.findOne({ username }).select("+password");
  assert(user, 422, "用户不存在");

  const isValid = require("bcrypt").compareSync(password, user.password);
  assert(isValid, 422, "密码错误");
  //返回token

  const token = jwt.sign({ id: user._id }, req.app.get("secret"));
  
  res.send({ user: user,token });
});

router.get("/login", (req, res) => {
  res.send("login api ok");
});

module.exports = router;
